package jwcb.javapjframework.common.redis.RedisService.service;

import lombok.RequiredArgsConstructor;
import lombok.val;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class RedissonLockService {
    /**
     * redis操作客户端
     */
    private final RedissonClient redissonClient;

    /**
     * 获取锁
     * @param lockKey 锁的key,唯一标识,建议模块名+唯一键
     * @param expire 超时时间,单位毫秒,-1则自动续期
     * @return 获取到锁的RLock实例,为null则获取失败
     */
    public RLock acquireAndWait(String lockKey, long expire) {
        try {
            final RLock lockInstance = redissonClient.getLock(lockKey);
            // 如果tryLock指定了leaseTime > 0 就不会续期 ,< 0 则开始看门狗功能 默认有效时间是30s,每隔10s进行看门狗检测
            lockInstance.lock(expire, TimeUnit.MILLISECONDS);
            return lockInstance;
        }catch (Exception e) {
            return null;
        }
    }


    /**
     * 获取锁
     * @param lockKey 锁的key,唯一标识,建议模块名+唯一键
     * @param expire 超时时间,单位毫秒,-1则自动续期
     * @return 获取到锁的RLock实例,为null则获取失败
     */
    public RLock acquireNoWait(String lockKey, long expire) {
        try {
            final RLock lockInstance = redissonClient.getLock(lockKey);
            // 如果tryLock指定了leaseTime > 0 就不会续期 ,< 0 则开始看门狗功能 默认有效时间是30s,每隔10s进行看门狗检测
            boolean acquire = lockInstance.tryLock(expire, TimeUnit.MILLISECONDS);
            return acquire ?  lockInstance : null;
        }catch (Exception e) {
            return null;
        }
    }


    public boolean releaseLock(RLock lockInstance) {
        if(lockInstance.isHeldByCurrentThread()) {
            lockInstance.unlock();
            return true;
        }
        return false;
    }
}
